package com.tn.controller.producer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.hifong45.Kv;
import com.gitee.hifong45.Ret;
import com.tn.annotation.LogRequestInfo;
import com.tn.controller.alarm.common.constants.Constants;
import com.tn.controller.alarm.common.constants.RpmConstants;
import com.tn.controller.alarm.common.model.InputVO;
import com.tn.controller.alarm.common.model.OutputVO;
import com.tn.controller.alarm.common.model.external.producer.vo.TaskInfoDispatchVo;
import com.tn.controller.alarm.common.model.external.producer.vo.TaskInfoVo;
import com.tn.controller.alarm.common.model.external.producer.vo.WhiteListMemberVO;
import com.tn.controller.alarm.common.model.external.subsystem.vo.ExitPermitVO;
import com.tn.controller.alarm.common.model.external.subsystem.vo.WeighInstructionsVO;
import com.tn.controller.alarm.common.model.producer.vo.ProQueryWeighLogVO;
import com.tn.controller.alarm.common.model.producer.vo.WeighLog4ProVO;
import com.tn.controller.alarm.common.model.rpm.InRadiusCheckParamDTO;
import com.tn.controller.alarm.common.model.weigh.vo.WeighLogInfoVO;
import com.tn.exception.BatchProcessFailedException;
import com.tn.service.external.producer.IProducerService;
import com.tn.service.external.producer.impl.ProducerServiceImpl;
import com.tn.service.rpm.RpmServeService;
import com.tn.utils.JsonUtil;
import com.tn.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 生产系统对接controller
 *
 * @program: tn_aucy_java
 * @author: yangjiayao
 * @create: 2021/12/03
 */
@RestController
@RequestMapping("/producer")
@Slf4j
public class ProducerController {
    @Autowired
    private RpmServeService rpmServeService;

    /**
     * service
     */
    private IProducerService producerService;

    @Resource
    private ProducerServiceImpl producerServiceImpl;

    public static boolean ifCallProducerApi = true;

    /**
     * 注入
     *
     * @param producerService service
     */
    @Autowired
    public void setProducerService(IProducerService producerService) {
        this.producerService = producerService;
    }

    /**
     * 添加白名单
     *
     * @param members 添加列表
     * @return 添加结果
     */
//    @LogRequestInfo
//    @RequestMapping("/addWhiteListMember")
//    public OutputVO<Object> addWhiteListMember(@RequestBody InputVO<List<WhiteListMemberVO>> members) {
//        OutputVO<Object> response = new OutputVO<>();
//        try {
//            response = producerService.addWhiteListMember(members);
//        } catch (BatchProcessFailedException e) {
//            response.setStatus(Constants.OtherSys.STATUS.UNKNOWN.getCode());
//            response.setInfo(Constants.OtherSys.STATUS.UNKNOWN.getMessage());
//        }
//        return response;
//    }

//        @LogRequestInfo
//        @RequestMapping("/addWhiteListMember")
//        public OutputVO<Object> addWhiteListMember(@RequestBody InputVO<List<WhiteListMemberVO>> members) {
//            OutputVO<Object> response = new OutputVO<>();
//            try {
//                for (WhiteListMemberVO member : members.getData()) {
//                    int w =producerService.queryOneTask(member.getTaskNo(), member.getLicense());
//                    if ( w ==0 ) {
//                    member.setOtherTaskInfo("001");
//                    producerService.addWhiteListMember(members);
//                } else {
//                        DecimalFormat decimalFormat=new DecimalFormat("000");
//                        for (int i = 0; i < members.getData().size(); i++) {
//                            String code = producerService.selectMaxOther();
//                            if (StringUtils.isEmpty(code)) {
//                                code = "001";
//                            }
//                            int num=Integer.parseInt(code)+1;
//                            String k=decimalFormat.format(num);
//                            code = "";
//                            code += k;
//                            members.getData().get(i).setOtherTaskInfo(code);
//                            response = producerService.addWhiteListMember(members);
//                        }
//                    }
//                }
//            } catch (BatchProcessFailedException e) {
//                response.setStatus(Constants.OtherSys.STATUS.UNKNOWN.getCode());
//                response.setInfo(Constants.OtherSys.STATUS.UNKNOWN.getMessage());
//            }
//            return response;
//        }

    @LogRequestInfo
    @RequestMapping("/addWhiteListMember")
    public OutputVO<Object> addWhiteListMember(@RequestBody InputVO<List<WhiteListMemberVO>> members) {
        OutputVO<Object> response = new OutputVO<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            for (WhiteListMemberVO member : members.getData()) {
                try {
                    member.setPositionsJson(objectMapper.writeValueAsString(member.getPositions()));
                }catch (Exception e){
                    log.error("白名单位置信息转换失败:{}",e.getMessage());
                }
                int w =producerService.queryOneTask(member.getTaskNo(), member.getLicense());
                if ( w ==0 ) {
                    member.setOtherTaskInfo("001");
                    producerService.addWhiteListMember(members);
                } else {
                    //修改此条任务号对应的过皮或过毛状态为2 已取消
                    producerService.updWeighState(member.getTaskNo(),member.getLicense());
                    DecimalFormat decimalFormat=new DecimalFormat("000");
                    for (int i = 0; i < members.getData().size(); i++) {
                        String code = producerService.selectMaxOther(member.getTaskNo(),member.getLicense());
                        if (StringUtils.isEmpty(code)) {
                            code = "001";
                        }
                        int num=Integer.parseInt(code)+1;
                        String k=decimalFormat.format(num);
                        code = "";
                        code += k;
                        members.getData().get(i).setOtherTaskInfo(code);
                        response = producerService.addWhiteListMember(members);
                    }
                }
            }
        } catch (BatchProcessFailedException e) {
            response.setStatus(Constants.OtherSys.STATUS.UNKNOWN.getCode());
            response.setInfo(Constants.OtherSys.STATUS.UNKNOWN.getMessage());
        }
        return response;
    }

//
//    /**
//     *本地查询任务信息
//     */
//    @LogRequestInfo
//    @RequestMapping("/quWhiteListMess")
//    public Ret<Object> quWhiteListMess(@RequestParam("license") String license) {
//        return Ret.Ok(producerService.quWhiteListMess(license));
//    }


    /**
     *铲车司机查看派工单
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/selectAllLicense")
    public Ret<Object> selectAllLicense(@RequestBody Map<String,String> map) throws Exception {
        return Ret.Ok(producerService.selectAllLicense(map));

    }


    /**
     * 理货开始
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/insertbindLicense")
    public Ret<Object> insertbindLicense(@RequestBody Map<String,String> map) throws Exception {
        producerService.insertbindLicense(map);
        return Ret.Ok();
    }


    /**
     * 理货结束
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/deletebindLicense")
    public Ret<Object> deletebindLicense(@RequestBody Map<String,String> map) throws Exception {
        producerService.deletebindLicense(map);

        return Ret.Ok();
    }


    /**
     * 撤销白名单
     *
     * @param members 撤销列表
     * @return 撤销结果
     */
    @LogRequestInfo
    @RequestMapping("/cancelWhiteListMember")
    public OutputVO<Object> cancelWhiteListMember(@RequestBody InputVO<List<WhiteListMemberVO>> members) {
        OutputVO<Object> response = new OutputVO<>();
        try {
            response = producerService.cancelWhiteListMember(members);
        } catch (BatchProcessFailedException e) {
            response.setStatus(Constants.OtherSys.STATUS.UNKNOWN.getCode());
            response.setInfo(Constants.OtherSys.STATUS.UNKNOWN.getMessage());
        }
        return response;
    }

    /**
     * 查询车辆过磅数据
     *
     * @param param
     * @return
     */
    @LogRequestInfo
    @RequestMapping("/queryWeighLog")
    public OutputVO<List<WeighLog4ProVO>> queryWeighLog(@RequestBody InputVO<ProQueryWeighLogVO> param) {
        if (null == param.getData()) {
            return new OutputVO<>(producerService.queryWeightLog(new ProQueryWeighLogVO()));
        }
        return new OutputVO<>(producerService.queryWeightLog(param.getData()));
    }

//    /**
//     * 新增理货任务
//     *
//     * @param  理货任务
//     * @return 新增结果
//     */
//    @Deprecated
//    @LogRequestInfo
//    @RequestMapping("/addTallyTask")
//    public OutputVO<Object> addTallyTask(@RequestBody InputVO<TallyTaskInfoDO> tallyTask) {
//        producerService.addTallyTask(tallyTask.getData());
//        return new OutputVO<>();
//    }

    @PostMapping("/task")
    public OutputVO<Object> doTaskInfo(@RequestBody InputVO<List<TaskInfoVo>> invo) {
        List<TaskInfoVo> tiLst = invo.getData();

        for(TaskInfoVo vo : tiLst) {
            Integer oprType = vo.getOprType(); // 0:加,1:改,2:删
            if(oprType == Constants.OPERATE_ADD) {
                log.info("添加任务:"+ JsonUtil.obj2String(vo));
                producerServiceImpl.addTaskInfo(vo);
            } else if(oprType == Constants.OPERATE_UPDATE) {
                log.info("更新任务:"+ JsonUtil.obj2String(vo));
                producerServiceImpl.updateTaskInfo(vo);
            } else if(oprType == Constants.OPERATE_DELETE) {
                log.info("删除任务:"+ JsonUtil.obj2String(vo));
                producerServiceImpl.deleteTaskInfo(vo);
            }
        }

        return new OutputVO<>();
    }

    @RequestMapping(value = "testDistanceTask", method = RequestMethod.GET)
    public void testDistanceTask() {
        rpmServeService.sendInRadiusCheck(
                InRadiusCheckParamDTO.builder().centraltag("1849").taglist(Collections.singletonList("a1"))
                        .radius(2000f).direction(Constants.DETECTION_TASK_DIRECTION).build(),
                RpmConstants.RMPACTIONTYPE.UPDATE.getType());
    }

    @GetMapping("/setcallapi")
    public Ret<Object> doCallApi(Integer call) {
        if(call != null) {
            ifCallProducerApi = call > 0;
        }
        return Ret.Ok(Kv.of("ifCallProducerApi", ifCallProducerApi));
    }

    @RequestMapping("test")
    public void test(@RequestBody ExitPermitVO params) {
        producerService.reportGateResult(params);
    }


    @RequestMapping("testWeight")
    public void testWeight(@RequestBody WeighInstructionsVO params) {
        producerService.reportWeighResult(params);
    }


    @PostMapping("/batch-insert-dispatch")
    public OutputVO<Object> batchInsertDispatch(@RequestBody InputVO<TaskInfoVo> invo) {
        TaskInfoVo taskInfoVo = invo.getData();
        producerServiceImpl.batchInsertDispatch(taskInfoVo);
        return new OutputVO<>();
    }

    @PostMapping("/update-dispatch")
    public OutputVO<Object> updateDispatch(@RequestBody InputVO<TaskInfoDispatchVo> invo) {
        TaskInfoDispatchVo taskInfoDispatchVo = invo.getData();
        OutputVO<Object> outputVO=producerServiceImpl.updateDispatch(taskInfoDispatchVo);
        return outputVO;
    }
}
